// pages/Order/TravelOrderDetail/TravelOrderDetail.js
//获取应用实例
const app = getApp()
const assetsAddress = app.globalData.global.assetsIp + '/' + app.globalData.global.assetsName;
import { queryPetTravelOrderForm , updatePetTravelOrderStatus , delPetTravelOrderForm , refundPetTravelOrderForm , payPetTravelOrder } from '../../../api/petOrder';
import { checkUserPasswordIsSet } from '../../../api/login';
import { queryUserWechatOpenId , getUserAccount , getUser } from '../../../api/user';
import { getChannel } from '../../../api/brand';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    assetsAddress: assetsAddress,
    safaBtm: wx.getSystemInfoSync().screenHeight - wx.getSystemInfoSync().safeArea.bottom,
    orderCode: '',
    order: {},
    showPayType: false,
    balance: 0,
    channel: [], // 支付方式
    payType: '1',
    user: {},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(options.orderCode){
      this.setData({
        orderCode: options.orderCode,
      })
      this._queryPetTravelOrderForm();
      this._getChannel();
      this._getUser();
      this._queryUserWechatUnionId();
      this._getUserAccount();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this._queryPetTravelOrderForm()
    setTimeout(()=>{
      wx.stopPullDownRefresh({
        success: (res) => {
          console.log(res,'刷新成功')
          wx.showToast({
            title: '刷新成功',
            icon: 'none',
          })
        },
      })
    },1000)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    let userId = wx.getStorageSync('userId') ?? 10;
    return {
      path: '/pages/Welcome/Welcome?scene='+userId,
    }
  },
  // 获取订单详情
  _queryPetTravelOrderForm(){
    let _this = this;
    queryPetTravelOrderForm({orderCode: _this.data.orderCode,page: 0,size: 1})
    .then(res => {
      if(res.success){
        var order = res.data.content.length > 0 ? res.data.content[0] : {};
        if(order.orderStatus == '0'){
          wx.setNavigationBarTitle({
            title: `待支付：￥${order.totalPrice}`,
          })
          var reg = new RegExp(/-/,'g');
          var createTime = order.createTime.replace(reg,'/');
          console.log(createTime,'createTime');
          var closeTime = new Date(createTime).getTime() - new Date().getTime() + 30 * 60 * 1000;
          console.log(closeTime,'closeTime')
          order.closeTime = closeTime;
        }
        _this.setData({
          order: order,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  timeFinish(){
    console.log('倒计时结束');
    this._queryPetTravelOrderForm();
  },
  // 去下单
  submitOrder(){
    let _this = this;
    _this.setData({
      showPayType: true
    })
  },
  // 下单
  _submitOrder(){
    let _this = this;
    _this.pay({orderCode:_this.data.orderCode,payType:_this.data.payType});
    // const { userName , phone , storeId , petId , quantity , remarks } = _this.data;
    // submitPetTravelOrder({phone: phone,userName: userName,petId: petId,storeId: storeId,quantity: quantity,remarks: remarks,goodsId: _this.data.goods.id})
    // .then(res => {
    //   if(res.success){
    //     _this.pay({orderCode:res.data.orderCode,payType:_this.data.payType});
    //   }else{
    //     wx.showToast({
    //       title: res.errMessage,
    //       icon: 'none',
    //     })
    //   }
    // })
  },
  pay({orderCode,payType,amount}){
    let _this = this;
    payPetTravelOrder({payType: payType,orderCode: orderCode,openId: _this.data.unionid,payPassword: payType == '1' ? _this.data.payPassword : null}).then(res => {
      if(res.success){
        _this.wechatPay({orderCode: orderCode,payType: payType,wechatSign: res.data});
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 支付
  wechatPay({orderCode,payType,wechatSign}){
    let _this = this;
    if(_this.data.payType == 1){
      wx.navigateTo({
        url: `/pages/Order/SubscribeSuccess/SubscribeSuccess?type=1&orderCode=${orderCode}`,
      })
    }else{
      // console.log(JSON.parse(wechatSign),'jsonData');
      var order = JSON.parse(wechatSign)
      // TODO微信支付
      wx.requestPayment({
        timeStamp: order.timeStamp.toString(),
        nonceStr: order.nonceStr,
        package: order.package,
        signType: order.signType,
        paySign: order.paySign,
        success: () => {
          wx.navigateTo({
            url: `/pages/Order/SubscribeSuccess/SubscribeSuccess?type=1&orderCode=${orderCode}`,
          })
        },
        fail: (err) => {
          console.log(err,'err')
          wx.showToast({
            title: '取消支付',
            icon: 'none',
          })
        }
      })
    }
  },
  // 余额支付校验密码成功
  sonSubmitOrder(e){
    console.log(e,'e')
    this.setData({
      payPassword: e.detail,
    })
    this._submitOrder();
  },
  // 校验是否设置过支付密码
  _checkUserPasswordIsSet(){
    let _this = this;
    return new Promise((resolve,reject) => {
      checkUserPasswordIsSet({})
      .then(res => {
        if(res.success){
          resolve(true)
        }else{
          resolve(false)
        }
      })
    })
  },
  // 获取用户的Openid
  _queryUserWechatUnionId(){
    let _this = this;
    wx.login({
      success: (logRes) => {
        queryUserWechatOpenId({code: logRes.code})
        .then(res => {
          if(res.success){
            _this.setData({
              unionid: res.data.openid
            })
          }else{
            wx.showToast({
              title: res.errMessage,
              icon: 'none',
            })
          }
        })
      }
    })
  },
  // 获取通道配置信息
  _getChannel(){
    let _this = this;
    getChannel({})
    .then(res => {
      if(res.success){
        var list = [];
        for (let index = 0; index < res.data.content.length; index++) {
          const item = res.data.content[index];
          if((item.channelName.indexOf('微信支付') != -1 || item.channelName.indexOf('余额支付') != -1)){
            list.push(item);
          }
        }
        console.log(list,'支付通道')
        _this.setData({
          channel: list,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取用户账户余额
  _getUserAccount(){
    let _this = this;
    getUserAccount({})
    .then(res => {
      if(res.success){
        _this.setData({
          balance : res.data.balance,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none'
        })
      }
    })
  },
  onClose(){
    this.setData({showPayType: false})
  },
  // 切换支付方式
  selPayType(e){
    const item = e.target.dataset.item||e.currentTarget.dataset.item;
    this.setData({
      payType: item.payType,
    })
  },
  // 确认支付
  async popPay(){
    let _this = this;
    this.onClose();
    if(_this.data.payType == 1){
      if(_this.data.order.totalPrice > _this.data.balance){
        wx.showToast({
          title: '当前余额不足，请更换其他支付方式.',
          icon: 'none'
        })
        return;
      }
      const isSetPayPassword = await _this._checkUserPasswordIsSet();
      if(!isSetPayPassword){
        if(_this.data.user.phone.length != 11){
          wx.showModal({
            title: '温馨提示',
            content: '当前暂未设置交易密码，设置交易密码之前需要绑定手机号，是否前往绑定？',
            success: (modal) =>{
              if(modal.confirm){
                wx.navigateTo({
                  url: '/pages/Users/BindPhone/BindPhone',
                })
              }
            },
          })
          return;
        }
        wx.showModal({
          title: '温馨提示',
          content: '暂未设置交易密码，是否前往设置？',
          success: (modal) =>{
            if(modal.confirm){
              wx.navigateTo({
                url: '/pages/Users/UpdatePayPassword/UpdatePayPassword',
              })
            }
          },
        })
        return;
      }
      const child = _this.selectComponent('.pay-passwordAuth');
      console.log(child,'child')
      child.clearPassword();
      child.openPayAuth();
    }else{
      _this._submitOrder();
    }
  },
  // 获取用户个人信息
  _getUser(){
    let _this = this;
    getUser({})
    .then(res => {
      if(res.success){
        _this.setData({
          user: res.data,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 取消订单
  cancelOrder(){
    let _this = this;
    wx.showModal({
      title: '温馨提示',
      content: '是否取消当前订单？',
      complete: (res) => {
        if (res.confirm) {
          updatePetTravelOrderStatus({orderCode: _this.data.orderCode,orderStatus: '2'})
          .then(res => {
            if(res.success){
              wx.showToast({
                title: '取消成功',
                icon: 'success'
              });
              _this._queryPetTravelOrderForm();
              const eventChannel = _this.getOpenerEventChannel()
              eventChannel.emit('updateOrder',);
            }else{
              wx.showToast({
                title: res.errMessage,
                icon: 'none',
              })
            }
          })
        }
      }
    })
  },
  // 删除订单
  delOrder(){
    let _this = this;
    wx.showModal({
      title: '温馨提示',
      content: '是否删除当前订单？',
      complete: (res) => {
        if (res.confirm) {
          delPetTravelOrderForm({orderCode: _this.data.orderCode,})
          .then(res => {
            if(res.success){
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              });
              const eventChannel = _this.getOpenerEventChannel()
              eventChannel.emit('updateOrder',);
              wx.navigateBack();
            }else{
              wx.showToast({
                title: res.errMessage,
                icon: 'none',
              })
            }
          })
        }
      }
    })
  },
  // 退款
  refundOrder(){
    let _this = this;
    wx.showModal({
      title: '温馨提示',
      content: '是否对当前订单申请退款？',
      complete: (res) => {
        if (res.confirm) {
          refundPetTravelOrderForm({orderCode: _this.data.orderCode,})
          .then(res => {
            if(res.success){
              wx.showToast({
                title: '申请成功',
                icon: 'success'
              });
              _this._queryPetTravelOrderForm();
              const eventChannel = _this.getOpenerEventChannel()
              eventChannel.emit('updateOrder',);
            }else{
              wx.showToast({
                title: res.errMessage,
                icon: 'none',
              })
            }
          })
        }
      }
    })
  },
})